package com.will.client;


import com.will.client.adapter.MyInboundHandlerAdapter;
import com.will.client.heart.ConnectorIdleStateTrigger;
import com.will.client.listener.ConnectionListener;
import com.will.utils.ObjectCodec;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 杨明智
 * @version:1.0
 * @create 2019年01月10日 4:05 PM
 * @description rpc客户端
 **/
@Component
public class NettyClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(NettyClient.class);
    private Bootstrap bootstrap;
    private EventLoopGroup worker;
    private SocketChannel channel;

    public Bootstrap createBootstrap(Bootstrap bootstrap, EventLoopGroup eventLoop) {
        if (bootstrap != null) {
            final MyInboundHandlerAdapter handler = new MyInboundHandlerAdapter(this);
            bootstrap.group(eventLoop);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(handler);
                    socketChannel.pipeline().addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS));
                    socketChannel.pipeline().addLast(new LengthFieldPrepender(2));
                    socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 2, 0, 2));
                    socketChannel.pipeline().addLast(new ObjectCodec());
                    socketChannel.pipeline().addLast(new ConnectorIdleStateTrigger());
                }
            });
            bootstrap.remoteAddress("localhost", 12345);
            ChannelFuture future = bootstrap.connect().addListener(new ConnectionListener(this));
            channel = (SocketChannel) future.channel();
        }
        return bootstrap;
    }

    public void run() {
        worker = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        createBootstrap(bootstrap, worker);
    }

    /**
     * 发送消息字符串
     *
     * @param msg
     */
    public void sendObjectMsg(Object msg) {

        ChannelFuture future = channel.writeAndFlush(msg);
        future.addListener((ChannelFutureListener) channelFuture ->
                LOGGER.info("客户端手动发消息成功={}", msg));

    }

    //    /**
//     * @param cmd   元信息
//     * @param retry 重连次数
//     * @return
//     */
//    public Object remoteCall(final MethodInvokeMeta cmd, int retry) {
//        try {
//            CustomChannelInitializer initializer = new CustomChannelInitializer(cmd);
//            bootstrap.handler(initializer);
//            ChannelFuture future = bootstrap.connect(host, port).sync();
//            future.channel().closeFuture().sync();
//            Object response = initializer.getResponse();
//            LOGGER.info("⌜⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓[reponse]: {}" +
//                    "⌞⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓⎓", response);
//            return response;
//        } catch (InterruptedException e) {
//            retry++;
//            if (retry > MAX_RETRY_TIMES) {
//                throw new RuntimeException("调用错误");
//            } else {
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e1) {
//                    e1.printStackTrace();
//                }
//                LOGGER.info("第{}次尝试....失败", retry);
//                return remoteCall(cmd, retry);
//            }
//        }
//    }
}
